<!--
 * @Descripttion: 
 * @version: 
 * @Author: 宁乃楚
 * @Date: 2021-07-03 14:55:50
 * @LastEditors: 宁乃楚
 * @LastEditTime: 2021-07-07 16:04:07
-->
<template>
  <!-- 常用地址界面 -->
  <div class="address">
      <van-sticky :offset-top="0">
        <van-nav-bar
          title="常用地址"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
        />
      </van-sticky>
    <div class="usual_address">
      <van-cell
        v-for="item in addressData"
        :key="item.id"
      >
        <template #title>
          <span class="custom-title">{{
            item.province + item.city + item.area
          }}</span
          >
          <van-icon
            name="edit"
            size="20px"
            color="black"
            style="float:right"
            @click="
              changeAddress(
                item.id,
                item.username,
                item.telephone,
                item.address,
                item.province,
                item.city,
                item.area
              )
            "
          />
          <br />
          <span>{{ item.address }}</span>
          <van-icon
            name="cross"
            size="20px"
            style="float:right"
            color="black"
            @click="
              deleteAddress(
                item.id
              )
            "
          />
        </template>
        <template #label>
          <span class="custom-title">{{
            item.username + '  ' + item.telephone
          }}</span>
          
        </template>
        
      </van-cell>
      <div style="height: 120px"></div>
    </div>
    <button class="btn" @click="show = true">+新增常用地址</button>
    <van-action-sheet
      title="新增地址"
      v-model="show"
      @select="onSelect"
      @cancel="onCancel"
    >
      <van-form @submit="onSubmit">
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="tel"
          type="tel"
          name="tel"
          label="电话"
          placeholder="电话"
          :rules="[{ required: true, message: '请填写电话' }]"
        />
        <van-field
          readonly
          clickable
          name="area"
          :value="value"
          label="地区选择"
          placeholder="点击选择省市区"
          @click="showArea = true"
        />
        <van-popup v-model="showArea" position="bottom">
          <van-area
            :area-list="areaList"
            @confirm="onConfirm"
            @cancel="showArea = false"
          />
        </van-popup>
        <van-field
          v-model="addAddress"
          type="addAddress"
          name="addAddress"
          label="详细地址"
          placeholder="地址"
          :rules="[{ required: true, message: '请输入详细地址' }]"
        />

        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >提交</van-button
          >
        </div>
      </van-form>
    </van-action-sheet>
  </div>
</template>

<script>
// 引入vuex辅助函数
import { mapActions, mapState } from "vuex";
// 引入axios @指代src路径
// 引入axios
import { get, post } from "@/http/axios";
import Vue from "vue";
import { Form } from "vant";
import { Field } from "vant";
import { areaList } from "@vant/area-data";
Vue.use(Form);
Vue.use(Field);

export default {
  data() {
    return {
      address: [],
      show: false,
      value: "",
      showArea: false,
      areaList,
      username: "",
      tel: "",
      addAddress: "",
      addressList: [],
      addressId: "",
    };
  },
  computed: {
    // 获取常用地址的数据
    ...mapState("address", ["addressData"]),
     // 引入user vuex中的方法
    ...mapState("user", ["userInfo"]),
  },
  methods: {
    // 引入获取常用地址数据的方法
    ...mapActions("address", ["getAllAddressData"]),
    // 引入user vuex中的方法
    ...mapActions("user", ["getUserInfo"]),
    // 返回上一个页面
    onClickLeft() {
      this.$router.go(-1);
    },
    onSelect(item) {
      console.log(item);
      this.show = false;
      this.$toast({
        message: item.name,
        duration: 500,
      });
    },
    // 查询常用地址
    queryAddress(userId) {
      // 定义参数
      let data = {
        page: 1,
        pageSize: 100,
        userId:userId
      };
      this.getAllAddressData(data);
    },
    onConfirm(values) {
      this.value = values
        .filter((item) => !!item)
        .map((item) => item.name)
        .join("/");
      this.showArea = false;
    },
    changeAddress(a, b, c, d, e,f,g) {
      this.show = true;
      (this.username = b), (this.tel = c), (this.value = e+'/'+f+'/'+g);
      this.addAddress = d;
      this.addressId = a;
    },
    async deleteAddress(a){
      let data={
        id:a
      }
      let res = await get("/address/deleteById", data);
      // 给用户一个成功或失败的提示
      if (res.status == 200) {
        this.$notify({
          message: res.data.message,
          background: "pink",
          duration: 1000,
        });
        this.show = false;
        this.queryAddress(this.userInfo.id);
      } else {
        this.$notify.error(res);
      }
    },
    // 新增地址
    async onSubmit(values) {
      this.addressList = this.value.split("/");
      let data = {
        id: this.addressId,
        userId:this.userInfo.id,
        username: values.username,
        telephone: values.tel,
        province: this.addressList[0],
        city: this.addressList[1],
        area: this.addressList[2],
        address: this.addAddress,
      };
      let res = await post("/address/saveOrUpdate", data);
      // 给用户一个成功或失败的提示
      if (res.status == 200) {
        this.$notify({
          message: res.data.message,
          background: "pink",
          duration: 1000,
        });
        this.show = false;
        this.queryAddress(this.userInfo.id);
      } else {
        this.$notify.error(res);
      }
    },
    onCancel() {
      this.id = "";
      (this.username = ""), (this.tel = ""), (this.addAddress = "");
      this.value = "";
    },
  },
  created() {
    // 自动获取用户数据
    this.getUserInfo().then(res=>{
      // 自动获取订单数据
      this.queryAddress(this.userInfo.id);
    })
  },
};
</script>

<style scoped>
.van-cell__label {
  width: 300px;
}
.btn {
  position: fixed;
  width: 90%;
  left: 5%;
  height: 40px;
  color: white;
  bottom: 4em;
  background-color: red;
  border: none;
  border-radius: 999px;
}
.cell {
  display: flex;
}
.van-cell__title {
  max-width: 100%;
  color: black;
}
.address /deep/ .van-nav-bar__title {
  color: white !important;
  font-size: 16px;
}
.address /deep/ .van-nav-bar {
  background-color: #fa5882;
  margin: 0;
  font-size: 16px;
}
.address /deep/ .van-nav-bar__text {
  color: white !important;
  font-size: 16px;
}
.address .van-nav-bar /deep/ .van-icon {
  color: white !important;
  font-size: 16px;
}
.van-cell__label {
  width: 100%;
  color: skyblue;
}
</style>